<template>
  <div class="base-container">
    <t-form
      ref="form"
      :data="queryParams"
      label-width="80"
      @submit="
        () => {
          this.pagination.current = 1;
          this.queryParams.pageNum = 1;
          this.getList();
        }
      "
      @reset="
        () => {
          this.pagination.current = 1;
          this.queryParams.pageNum = 1;
          this.getList();
        }
      "
    >
      <t-row style="border-bottom: 1px solid #e5e6eb; margin-bottom: 10px">
        <t-col :span="11" class="query-form-inline">
          <t-form-item label="平台名称" name="name">
            <t-input v-model="queryParams.name" clearable placeholder="请输入平台名称" style="width: 240px" />
          </t-form-item>
          <t-form-item label="平台类别" name="platformCategory">
            <t-select
              style="width: 240px"
              clearable
              v-model="queryParams.platformCategory"
              :options="dict.type.platform_category"
            >
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="1" class="operation-container">
          <t-button theme="primary" type="submit"> 查询</t-button>
          <t-button theme="default" variant="base" type="reset">重置</t-button>
        </t-col>
      </t-row>
    </t-form>
    <div class="btn-group-inline">
      <t-button @click="apply" variant="outline" theme="primary">
        <t-icon name="add" slot="icon" />
        添加报告
      </t-button>
    </div>
    <t-table
      rowKey="index"
      size="small"
      :data="data"
      :columns="columns"
      hover
      :pagination="pagination"
      :loading="dataLoading"
      :sort="sort"
      :hideSortTips="true"
      @sort-change="sortChange"
    >
      <template #platformName="{ row }">
        <t-link
          @click="
            dialog.objId = row.platformId;
            dialog.header = row.name;
            dialog.open_project_detail = true;
          "
          hover="color"
          theme="primary"
          >{{ row.platformName }}</t-link
        >
      </template>

      <!--      <template #name="{ row }">-->
      <!--        <t-link @click="dialog.objId=row.id;dialog.header=row.name;dialog.open_project_detail=true" hover="color" theme="primary">{{row.name}}</t-link>-->
      <!--      </template>-->
      <template #platformCategory="{ row }">
        {{ row.platformCategory | filterByDict(dict.type.platform_category) }}
      </template>
      <template #bg="{ row }">
        <a class="t-button-link" target="_blank" v-for="(item, index) in row.bg" :href="item.url" :key="index">
          {{ item.name }}
        </a>
      </template>
      <!-- <template #op="{ row }">
        <t-button size="small" variant="text" class="t-button-link">
          <t-icon name="info-circle" slot="icon" />
          详情
        </t-button>
        <t-button size="small" @click="edit(row)" variant="text" class="t-button-link">
          <t-icon name="edit-1" slot="icon" />
          编辑
        </t-button>
        <t-button theme="danger" @click="deleteItem(row)" size="small" variant="text" class="t-button-link">
          <t-icon name="delete" slot="icon" />
          删除
        </t-button>
      </template> -->
    </t-table>
    <peopleInfo @closeBzhDialog="closeBzhDialog" v-if="detailDialog.visible" :dialogInfo="detailDialog"></peopleInfo>
    <platform-detail-dialog
      :header="dialog.header"
      :objId="dialog.objId"
      :visible.sync="dialog.open_project_detail"
      v-if="dialog.open_project_detail"
    ></platform-detail-dialog>
    <t-dialog
      :visible.sync="dialogVisible"
      :confirmBtn="null"
      width="25%"
      :header="header"
      :cancelBtn="null"
      :onClose="closeDialog"
      v-if="dialogVisible"
    >
      <t-form ref="form2" @submit="onSubmit" :data="formData" labelWidth="160px" :rules="rules">
        <t-form-item label="报告名称：" name="name">
          <t-input v-model="formData.name" placeholder="请输入报告名称" style="width: 240px" />
        </t-form-item>
        <t-form-item label="报告日期：" name="reportDate">
          <t-date-picker v-model="formData.reportDate" style="width: 240px"></t-date-picker>
        </t-form-item>
        <t-form-item label="上传相关文件:" name="fileIds" style="padding-bottom: 10px">
          <file-upload
            accept="application/pdf,image/*"
            :file-list="projectFileData[0].fileLists"
            :multiple="true"
            tips="限制pdf、图片"
            v-model="projectFileData[0].fileIds"
            :moduleKey="projectFileData[0].moduleKey"
          >
            <t-button variant="outline">
              <t-icon name="cloud-upload" slot="icon" />
              点击上传
            </t-button>
          </file-upload>
        </t-form-item>
        <t-row>
          <t-col :span="12" class="operation-container">
            <t-button theme="default" variant="outline" type="reset" @click="closeDialog">取消</t-button>
            <t-button theme="primary" type="submit"> 提交</t-button>
          </t-col>
        </t-row>
      </t-form>
    </t-dialog>
  </div>
</template>

<script>
import peopleInfo from '@/pages/kjpt/components/people-info.vue';
import platformDetailDialog from '@/pages/kjpt/platform/components/platform-detail-dialog.vue';
import { getFiles } from '@/api/common';
import FileUpload from '@/components/FileUpload/index.vue';

export default {
  name: 'platformReport-myList',
  dicts: ['platform_category'],
  components: {
    peopleInfo,
    platformDetailDialog,
    FileUpload,
  },
  data() {
    return {
      projectFileData: [
        {
          id: 1,
          c1: '评估报告',
          c2: '是',
          moduleKey: 'platformPGBG',
          fileIds: [],
          fileLists: [],
        },
      ],
      rules: {
        name: [
          {
            required: true,
            message: '报告名称不能为空',
          },
        ],
        reportDate: [
          {
            required: true,
            message: '报告日期不能为空',
          },
        ],
        fileIds: [
          {
            required: true,
            message: '附件不能为空',
          },
        ],
      },
      formData: {},
      header: '',
      dialogVisible: false,
      detailDialog: {
        id: '',
        header: '',
        visible: false,
      },
      sort: [],
      nowRow: '',
      dialog: {
        open_project_detail: false,
        header: '',
        objId: 0,
        open_approve_list: false,
        open_project_file: false,
      },
      dictTypes: {},
      projectCategoryOptions: [],
      columns: [
        {
          colKey: 'platformName',
          title: '平台名称',
          align: 'center',
          width: 220,
        },
        {
          colKey: 'name',
          title: '报告名称',
          align: 'center',
          width: 180,
        },
        {
          colKey: 'reportDate',
          title: '报告日期',
          align: 'center',
          width: 180,
        },
        {
          colKey: 'bg',
          title: '报告文件',
          align: 'center',
          width: 120,
          fixed: 'right',
        },
        // {
        //   colKey: "startReportDate",
        //   title: "报告日期区间",
        //   align: "center",
        //   width: 180
        // },
        // {
        //   colKey: "endReportDate",
        //   title: "报告日期区间",
        //   align: "center",
        //   width: 180
        // },
        // {
        //   colKey: "op",
        //   title: "操作",
        //   align: "center",
        //   width: 220,
        //   fixed: 'right'
        // },
      ],
      data: [],
      dataLoading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        platformCategory: '',
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showPageSize: true,
        pageSizeOptions: [10, 20, 30, 50],
        showFirstAndLastPageBtn: false,
        onChange: (pageInfo) => {
          Object.assign(this.pagination, pageInfo);
          this.queryParams.pageNum = pageInfo.current || 1;
          this.queryParams.pageSize = pageInfo.pageSize;
          this.getList();
        },
      },
    };
  },
  async created() {
    this.getList();
  },
  methods: {
    onSubmit() {
      this.$refs.form2.validate().then((validateResult) => {
        if (!validateResult.name && !validateResult.reportDate && this.projectFileData[0].fileIds) {
          validateResult = true;
        }
        if (validateResult === true) {
          this.formData.platformId = this.platId;
          const sysAttMainVo = {
            sysAttMainIds: this.projectFileData[0].fileIds,
          };
          delete this.formData.fileIds;
          this.formData.sysAttMainVo = sysAttMainVo;
          console.log(this.nowRow);
          this.formData.platformId = this.nowRow.platformId;
          if (this.nowRow.platformId) {
            this.$api.kjpt.platformReport
              .edit(this.formData)
              .then((res) => {
                this.$message.success('修改成功');
                this.dialogVisible = false;
                this.formData = {};
                this.getList();
              })
              .catch((err) => {
                this.$message.error(err.toString());
              });
          }
        } else {
          this.$message.error('字段不能为空');
        }
      });
    },
    closeDialog() {
      this.dialogVisible = false;
      this.formData = {};
      this.getList();
    },
    edit(row) {
      this.nowRow = row;
      getFiles(row.id).then((res) => {
        const files = {};
        res.data.forEach((item) => {
          if (!files[item.moduleKey]) {
            files[item.moduleKey] = [];
          }
          files[item.moduleKey].push({
            name: item.fileName,
            url: item.fullFilePath,
            id: item.id,
            filePath: item.filePath,
          });
          this.projectFileData[0].fileLists = files.platformPGBG || [];
          this.projectFileData[0].fileIds = files.platformPGBG?.map((val) => val.id) || [];
        });
        this.$api.kjpt.platformReport.get(row.id).then((response) => {
          this.formData = response.data;
          this.dialogVisible = true;
        });
      });
    },
    deleteItem(row) {
      const confirmDia = this.$dialog.confirm({
        header: '系统提示',
        body: `是否确认删除？`,
        theme: 'warning',
        onConfirm: ({ e }) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          });
          this.$api.kjpt.platformReport
            .delete(row.id)
            .then((res) => {
              this.getList();
              this.$message.success('删除成功');
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            })
            .catch((e) => {
              confirmDia.update({
                confirmBtn: {
                  loading: false,
                },
              });
              this.$message.error(e.toString());
            });
        },
      });
    },
    // 点击列表名字事件
    nameClick(row) {
      this.detailDialog.id = row.id;
      this.detailDialog.header = row.name;
      this.detailDialog.visible = true;
    },
    // 关闭详情弹框
    closeBzhDialog(data) {
      this.detailDialog.visible = data;
    },
    sortChange(sort) {
      this.sort = sort;
      let orderByColumn = [];
      let isAsc = [];
      if (sort instanceof Array) {
        orderByColumn = sort.map((val) => val.sortBy);
        isAsc = sort.map((val) => (val.descending ? `desc` : `asc`));
      } else {
        orderByColumn = [sort.sortBy];
        isAsc = [sort.descending ? `desc` : `asc`];
      }
      this.queryParams.orderByColumn = orderByColumn.join(',');
      this.queryParams.isAsc = isAsc.join(',');
      this.getList();
    },
    getList() {
      this.dataLoading = true;
      this.queryParams.pageNum = this.pagination.current || 1;
      this.$api.kjpt.platformReport
        .myList(this.queryParams)
        .then((response) => {
          this.pagination.total = response.total;
          this.data = response.rows;
          this.dataLoading = false;
          this.data.forEach(async (item, index) => {
            await getFiles(item.id)
              .then((res) => {
                const files = {};
                res.data.forEach((item) => {
                  if (!files[item.moduleKey]) {
                    files[item.moduleKey] = [];
                  }
                  files[item.moduleKey].push({
                    name: item.fileName,
                    url: item.fullFilePath,
                    id: item.id,
                    filePath: item.filePath,
                  });
                  this.$set(this.data[index], 'bg', files.platformPGBG || []);
                });
              })
              .catch((e) => {
                this.$message.error(e.toString());
              });
          });
        })
        .catch((e) => {
          this.dataLoading = false;
          this.$message.error(e.toString());
        });

      // getFiles(this.$route.params.id).then((res) => {
      //   const files = {}
      //   res.data.forEach((item) => {
      //     if (!files[item.moduleKey]) {
      //       files[item.moduleKey] = []
      //     }
      //     files[item.moduleKey].push({
      //       name: item.fileName,
      //       url: item.fullFilePath,
      //       id: item.id,
      //       filePath: item.filePath
      //     })
      //   })
      //   this.projectFileData[0].fileLists = files.projectLXGW || [];
      //   this.projectFileData[1].fileLists = files.projectBZCA || [];
      //   this.projectFileData[0].fileIds = files.projectLXGW?.map(val => val.id) || [];
      //   this.projectFileData[1].fileIds = files.projectBZCA?.map(val => val.id) || [];
      //   console.log( files)
      // }).catch((e) => {
      //   this.$message.error(e.toString());
      // });
    },
    apply() {
      this.$router.push(`/kjpt/runManagement/platformReport-apply`);
    },
    deleteProject(row) {
      const confirmDia = this.$dialog.confirm({
        header: '系统提示',
        body: `是否确认删除项目名称为"${row.projectName}"的数据项？`,
        theme: 'warning',
        onConfirm: ({ e }) => {
          confirmDia.update({
            confirmBtn: {
              loading: true,
            },
          });
          this.$api.kjxm.project
            .del(row.id)
            .then((res) => {
              this.getList();
              this.$message.success('删除成功');
              // 请求成功后，销毁弹框
              confirmDia.destroy();
            })
            .catch((e) => {
              confirmDia.update({
                confirmBtn: {
                  loading: false,
                },
              });
              this.$message.error(e.toString());
            });
        },
      });
    },
  },
};
</script>

<style scoped>
</style>
